package net.liteheaven.xblib.common.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import net.liteheaven.xblib.R;

public class ToastUtil {
    private interface IToastDisplayer {
        void show(BaseToastBuilder toastBuilder, String text);
    }

    private static class ImmediatelyDisplayer implements IToastDisplayer {
        private static Toast mLastToast = null;

        @Override
        public void show(BaseToastBuilder builder, String text) {
            if (mLastToast != null){
                mLastToast.cancel();
                mLastToast = null;
            }
            mLastToast = builder.build(text);

            builder.setText(mLastToast, text);
            mLastToast.show();
        }

    }

    private static abstract class BaseToastBuilder{
        protected Context mContext;
        public BaseToastBuilder(Context context) {
            if (context == null){
                throw new IllegalArgumentException("context cannot be null!");
            }

            mContext = context;
        }

        public abstract Toast build(String text);
        public abstract void setText(Toast t, String text);
    }

    private static class CommonToastBuilder extends BaseToastBuilder {
        public CommonToastBuilder(Context ctx) {
            super(ctx);
        }

        @SuppressLint("InflateParams")
        @Override
        public Toast build(String text) {
            Toast t = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);
            LayoutInflater li = LayoutInflater.from(mContext);
            View view = li.inflate(R.layout.common_toast, null);
            t.setView(view);
            t.setGravity(Gravity.CENTER, 0, 0);
            return t;
        }

        @Override
        public void setText(Toast t, String text) {
            View root = t.getView();
            TextView tv = (TextView)root.findViewById(R.id.text);
            tv.setText(text);
        }
    }

    public static void show(Context context, String text) {
        CommonToastBuilder builder = new CommonToastBuilder(context);
        ImmediatelyDisplayer displayer = new ImmediatelyDisplayer();
        displayer.show(builder, text);
    }
}
